package com.mio.web.controller.sellnetwork;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.durcframework.core.GridResult;
import org.durcframework.core.MessageResult;
import org.durcframework.core.UserContext;
import org.durcframework.core.controller.CrudController;
import org.durcframework.core.expression.ExpressionQuery;

import com.mio.web.common.MioUtil;
import com.mio.web.entity.product.Product;
import com.mio.web.entity.recommend.Recommand;
import com.mio.web.entity.sellnetwork.Sellnetwork;
import com.mio.web.entity.sellnetwork.SellnetworkSch;
import com.mio.web.entity.sys.SysUpload;
import com.mio.web.service.sellnetwork.SellnetworkService;
import com.mio.web.service.sys.SysUploadService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class SellnetworkController extends
		CrudController<Sellnetwork, SellnetworkService> {

	@Autowired
	private SysUploadService sysUploadService;
	
	@RequestMapping("/sellNetwork.do")
	public ModelAndView getRecommandJsp(HttpServletRequest request){
		ModelAndView model = new ModelAndView("/network.jsp");
		//获取登录用户
		model.addObject("loginUser",UserContext.getInstance().getUser());
		//每页显示5条数据
		int pageSize = 5;
		//获取当前页数以及总页数
		String pages = request.getParameter("pageStart");
		String pageTotal = request.getParameter("pageCount");
		ExpressionQuery query = new ExpressionQuery();
		query.addSort("sortId");
		query.setPageSize(pageSize);
		int pageNum  = 1;
		if(pages != null){
			pageNum = Integer.parseInt(pages);
			query.setStart((pageNum-1)*pageSize);
		}else{
			query.setStart(0);
		}
		//获取当前页数的销售网络
		List<Sellnetwork> sellnetworks = this.getService().find(query);
		model.addObject("sellnetworks",sellnetworks);
		//设置起始页数
		model.addObject("pageStart", pageNum);
		int pageCount = 0;
		//判断是否有总页数的值
		if(pageTotal != null){
			int total = Integer.parseInt(pageTotal);
			pageCount = total;
		}else{
			//查询美美推荐的总页数
			query = new ExpressionQuery();
			pageCount = this.getService().findTotalCount(query)/pageSize + 1;
		}
		//设置总页数
		model.addObject("pageCount",pageCount);
		return model;
	}
	
	//新增
	@RequestMapping("/addSellNetwork.do")
	public @ResponseBody
	Map<String, Object> addSellnetwork(Sellnetwork entity, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException   {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/sellNetwork/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				List<SysUpload> sysUploads = new ArrayList<SysUpload>();
				int count = 0;
				//店名缩略图
				String shopImg = "";
				while (iter.hasNext()) {
					System.out.println(iter.hasNext());
					count++;
					// 记录上传过程起始时的时间，用来计算上传时间
					int pre = (int) System.currentTimeMillis();
					// 取得上传文件
					MultipartFile file = multiRequest.getFile(iter.next());
					if (file != null) {
						// 取得当前上传文件的文件名称
						String myFileName = file.getOriginalFilename();
						// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
						if (!myFileName.trim().equals("")) {
							System.out.println(myFileName);
							// 重命名上传后的文件名
							File targetFile = MioUtil.getUploadFile(request, "sellNetwork", myFileName,response);
							file.transferTo(targetFile);
							
							SysUpload sysUpload = new SysUpload();
							sysUpload.setFileSize((int)file.getSize());
							sysUpload.setFileFullPath(relPath+myFileName);
							sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
							sysUpload.setFuncId("sellNetwork");
							sysUpload = sysUploadService.save(sysUpload);
							//拼接上传文件的id
							if(count == 1){
								shopImg = relPath+myFileName;
								entity.setsImgUrl(shopImg);
							}
							entity.setsImgUrl(sysUpload.getFileFullPath());
							sysUploads.add(sysUpload);
							
						}
					}
					// 记录上传该文件后的时间
					int finaltime = (int) System.currentTimeMillis();
					System.out.println(finaltime - pre);
				}
				
				//保存产品信息
				entity.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
				entity = this.getService().save(entity);
			}
		} catch (Exception e) {
			e.printStackTrace();
			resultMap.put("success", false);
			resultMap.put("info", e.getMessage());
		}
		resultMap.put("success", true);
		resultMap.put("info", entity);
		return resultMap;
	}

	//ɾ���¼
	@RequestMapping("/delSellnetwork.do")
	public @ResponseBody
	MessageResult delSellnetwork(Sellnetwork entity) {
		return this.delete(entity);
	}
	
	//�޸ļ�¼
	@RequestMapping("/updateSellnetwork.do")
	public @ResponseBody
	MessageResult updateSellnetwork(Sellnetwork entity, HttpServletRequest request,
			HttpServletResponse response) throws IllegalStateException, IOException   {
		int change0 = Integer.parseInt(request.getParameter("change0"));
		boolean flag = false;
		//表示修改
		if(change0>0){
			flag = true;
		}
		try {
			// 创建一个通用的多部分解析器
			CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
					request.getSession().getServletContext());
			// 判断 request 是否有文件上传,即多部分请求
			if (multipartResolver.isMultipart(request)) {
				String relPath = "/upload/sellNetwork/";
				// 转换成多部分request
				MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
				// 取得request中的所有文件名
				Iterator<String> iter = multiRequest.getFileNames();
				while (iter.hasNext()) {					
					if(flag){
						System.out.println("  "+iter.hasNext());
						// 记录上传过程起始时的时间，用来计算上传时间
						int pre = (int) System.currentTimeMillis();
						// 取得上传文件
						MultipartFile file = multiRequest.getFile(iter.next());
						if (file != null) {
							// 取得当前上传文件的文件名称
							String fileName = file.getOriginalFilename();
							// 如果名称不为“”,说明该文件存在，否则说明该文件不存在
							if (!fileName.trim().equals("")) {
								System.out.println(fileName);
								// 定义上传路径
								File targetFile = MioUtil.getUploadFile(request, "sellNetwork", fileName,response);
								file.transferTo(targetFile);
								SysUpload sysUpload = new SysUpload();
								sysUpload.setFileSize((int)file.getSize());
								sysUpload.setFileFullPath(relPath+fileName);
								sysUpload.setCreatedTime(MioUtil.getYMDHMSDateTime(new Date()));
								sysUpload.setFuncId("sellNetwork");
								sysUpload = sysUploadService.save(sysUpload);
								entity.setsImgUrl(sysUpload.getFileFullPath());
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();

		}
		return this.update(entity);
	}

	//������ѯ��ҳ����
	@RequestMapping("/listSellnetwork.do")
	public @ResponseBody
	GridResult listSellnetwork(SellnetworkSch searchEntitySch) {
		return this.query(searchEntitySch);
	}

	
	//������ѯ���������м�¼
	@RequestMapping("/listAllSellnetwork.do")
    public @ResponseBody Object listAllSellnetwork(SellnetworkSch searchEntitySch) {
        return this.queryAll(searchEntitySch);
    }

    //��ȡ��ϸ��Ϣ
	@RequestMapping("/getSellnetworkById.do")
    public @ResponseBody Sellnetwork getSellnetworkById(Sellnetwork entity) {
        return this.getService().get(entity.getId());
    }

}